package com.qkun.library.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.WallpaperManager;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.annotation.ColorInt;
import androidx.annotation.ColorRes;
import androidx.core.content.ContextCompat;

import com.qkun.library.base.BaseApplication;

import java.util.Arrays;
import java.util.List;

public class Utils {

    /**
     * 不包含应用名称的Toast
     * TODO: 6/1 0001 待考虑是否值得将 Toast 全局化（这有没有可能造成内存泄露之类的）
     */
    private static Toast sToast;

    private Utils() {

    }

    public static String getAndroidId() {
        return Settings.System.getString(BaseApplication.getAppContext().getContentResolver(), Settings.Secure.ANDROID_ID);
    }

    public static void makeToast(CharSequence msg, boolean isShortTime) {
        if (nonNull(sToast)) sToast.cancel();
        sToast = Toast.makeText(BaseApplication.getAppContext(), "", isShortTime ? Toast.LENGTH_SHORT : Toast.LENGTH_LONG);
        sToast.setText(msg);
        sToast.show();
    }

    public static boolean nonNull(Object o) {
        return o != null;
    }

    public static boolean isNull(Object o) {
        return o == null;
    }

    public static <T> T requireNonNull(T o) {
        if (isNull(o))
            throw new NullPointerException();
        return o;
    }

    public static boolean isPackageInstalled(String packageName) {
        PackageManager pm = BaseApplication.getAppContext().getPackageManager();
        List<PackageInfo> list = pm.getInstalledPackages(0);
        for (PackageInfo p : list) {
            if (p.packageName.equals(packageName)) {
                return true;
            }
        }
        return false;
    }

    public static void hideNavigationBar(Activity activity) {
        View decorView = activity.getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN;
        decorView.setSystemUiVisibility(uiOptions);
    }

    public static void showNavigationBar(Activity activity) {
        View decorView = activity.getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_VISIBLE;
        decorView.setSystemUiVisibility(uiOptions);
    }

    public static boolean isEmpty(List<?> list) {
        return isNull(list) || list.isEmpty();
    }

    public static boolean isSpace(final String str) {
        if (!TextUtils.isEmpty(str)) {
            for (char c : str.toCharArray()) {
                if (!Character.isWhitespace(c)) {
                    return false;
                }
            }
        }
        return true;
    }

    public static boolean isOfActivity(Intent intent) {
        return nonNull(intent) && nonNull(BaseApplication.getAppContext()
                .getPackageManager()
                .resolveActivity(intent, 0));
    }

    public static boolean isOfService(Intent intent) {
        return nonNull(intent) && nonNull(BaseApplication.getAppContext()
                .getPackageManager()
                .resolveService(intent, 0));
    }

    /**
     * 判断一个服务是否在运行
     *
     * @param serviceName service类的全称（包含了包名的）
     * @return
     */
    public static boolean isServiceInRunning(String serviceName) {
        if (!TextUtils.isEmpty(serviceName)) {
            ActivityManager activityManager = (ActivityManager) BaseApplication.getAppContext().getSystemService(Context.ACTIVITY_SERVICE);
            if (nonNull(activityManager)) {
                List<ActivityManager.RunningServiceInfo> serviceInfoList = activityManager.getRunningServices(Integer.MAX_VALUE);
                if (!isEmpty(serviceInfoList)) {
                    for (ActivityManager.RunningServiceInfo item : serviceInfoList) {
                        ComponentName name = item.service;
                        if (name.getClassName().equals(serviceName)) return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 将字符串前面的空格去掉
     *
     * @param str
     * @return
     */
    public static String trimL(String str) {
        if (!TextUtils.isEmpty(str)) {
            int i = 0;
            final int N = str.length();
            while ((i < N) && Character.isWhitespace(str.charAt(i))) {
                i++;
            }
            if (i > 0) str = str.substring(i);
        }
        return str;
    }

    /**
     * 将Uri转为真实的String路径
     *
     * @param uri
     * @return
     */
    public static String uriToPath(Uri uri) {
        if (nonNull(uri)) {
            String scheme = uri.getScheme();
            String path = null;
            if (isNull(scheme)) {
                path = uri.getPath();
            } else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
                path = uri.getPath();
            } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
                Cursor cursor = null;
                try {
                    cursor = BaseApplication.getAppContext().getContentResolver().query(uri,
                            new String[]{MediaStore.Images.ImageColumns.DATA},
                            null,
                            null,
                            null);
                    if (nonNull(cursor) && cursor.moveToFirst()) {
                        int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                        if (index > -1) {
                            path = cursor.getString(index);
                        }
                    }
                } catch (Exception e) {
                    MyLog.e(e);
                } finally {
                    if (nonNull(cursor)) {
                        cursor.close();
                    }
                }
            }
            return path;
        }
        return null;
    }

    public static void requestParentRemoveView(View view) {
        if (Utils.nonNull(view)) {
            ViewParent parent = view.getParent();
            if (Utils.nonNull(parent)) {
                if (parent instanceof ViewGroup) {
                    ((ViewGroup) parent).removeView(view);
                }
            }
        }
    }

    public static boolean isValidPackage(String pkg, int uid) {
        if (!TextUtils.isEmpty(pkg)) {
            final PackageManager pm = BaseApplication.getAppContext().getPackageManager();
            final String[] packages = pm.getPackagesForUid(uid);
            final int N = Utils.nonNull(packages) ? packages.length : 0;
            for (int i = 0; i < N; i++) {
                if (packages[i].equals(pkg)) {
                    return true;
                }
            }
        }
        return false;
    }

    public static int hash(Object... values) {
        return Arrays.hashCode(values);
    }

    public static void ensureClassLoader(Bundle bundle, Class<?> cls) {
        if (nonNull(bundle)) {
            bundle.setClassLoader(requireNonNull(cls).getClassLoader());
        }
    }

    /**
     * 获取壁纸
     *
     * @return
     */
    public static Drawable getWallpaper() {
        WallpaperManager wallpaperManager = WallpaperManager.getInstance(BaseApplication.getAppContext());
        return wallpaperManager.getDrawable();
    }

    @ColorInt
    public static int getColor(@ColorRes int colorId) {
        return ContextCompat.getColor(BaseApplication.getAppContext(), colorId);
    }

    public static int parseInt(CharSequence charSequence) {
        if (!TextUtils.isEmpty(charSequence)) {
            try {
                return Integer.parseInt(charSequence.toString());
            } catch (NumberFormatException e) {
                MyLog.e(e);
            }
        }
        return 0;
    }

    public static void disableTouch(View view, boolean disable) {
        if (Utils.nonNull(view)) {
            view.setClickable(disable);
            view.setFocusable(disable);
            view.setEnabled(disable);
        }
    }

    public static boolean isEnableTouch(View view) {
        return Utils.nonNull(view) && view.isEnabled() && view.isClickable() && view.isFocusable();
    }

    public static void disableTouch(Activity activity, boolean disable) {
        if (Utils.nonNull(activity)) {
            if (disable) {
                activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
            } else {
                activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
            }
        }
    }

    /**
     * 根据文件路径获取Uri（不需要通过FileProvider）
     *
     * @param fileAbsolutePath
     * @return
     */
    private Uri getContentUri(String fileAbsolutePath) {
        Uri contentUri = null;
        if (!TextUtils.isEmpty(fileAbsolutePath)) {
            Uri baseUri = MediaStore.Files.getContentUri("external");
            String[] projection = {MediaStore.MediaColumns._ID};
            String selection = MediaStore.MediaColumns.DATA + " = ?";
            String[] selectionArgs = new String[]{fileAbsolutePath};
            Cursor cursor = null;
            String providerPackageName = "com.android.providers.media.MediaProvider";
            BaseApplication.getAppContext().grantUriPermission(providerPackageName, baseUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
            MyLog.d("baseUri = " + baseUri
                    + " projection = " + Arrays.toString(projection)
                    + " selection = " + selection
                    + " selectionArgs = " + Arrays.toString(selectionArgs));
            try {
                cursor = BaseApplication.getAppContext().getContentResolver().query(baseUri,
                        projection,
                        selection,
                        selectionArgs,
                        null);
                if (nonNull(cursor) && cursor.moveToNext()) {
                    int type = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.MediaColumns._ID));
                    if (type != 0) {
                        long id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.MediaColumns._ID));
                        contentUri = Uri.withAppendedPath(baseUri, String.valueOf(id));
                    }
                }
            } catch (Exception e) {
                MyLog.e(e);
            } finally {
                if (nonNull(cursor)) {
                    cursor.close();
                }
            }
        }
        MyLog.d("contentUri = " + contentUri);
        return contentUri;
    }

}
